package cn.masterj.springcloud.config;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpResponse;
import reactor.core.publisher.Mono;

/**
 * @author masterJ
 * @create 2020-04-13 10:38
 */
@Configuration
@Slf4j
public class GlobalFilterConfig {

    @Bean
    @Order(1)
    public GlobalFilter customGlobalFilter() {
        return (exchange, chain) -> {
            log.info("**************filter 排序是1**************");
            // getFirst 是拿到参数中，如果是同名的key，就是第一个key的值
            String val = exchange.getRequest().getQueryParams().getFirst("name");
            if (StringUtils.isBlank(val)){
                log.info("*******name不能为空********");
                exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
        };
    }


    @Bean
    @Order(2)
    /**
     * pre，post，前置和后置过滤器
     */
    public GlobalFilter customGlobalPostFilter() {
        return (exchange, chain) -> {
            log.info("**************filter 排序是2**************");
            return chain.filter(exchange).then(
                Mono.fromRunnable(()->{
                    ServerHttpResponse response = exchange.getResponse();
                    log.info("******************response后置过滤器***********" + response.getClass());
                    response.getHeaders().add("myHead","hhhhh");
                })
            );
        };
    }


//    @Bean
//    public GlobalFilter customGlobalPostFilter() {
//        return (exchange, chain) -> chain.filter(exchange)
//                .then(Mono.just(exchange))
//                .map(serverWebExchange -> {
//                    //adds header to response
//                    serverWebExchange.getResponse().getHeaders().set("CUSTOM-RESPONSE-HEADER",
//                            HttpStatus.OK.equals(serverWebExchange.getResponse().getStatusCode()) ? "It worked": "It did not work");
//                    return serverWebExchange;
//                })
//                .then();
//    }
}
